from contextlib import contextmanager
from datetime import datetime
from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy
from sqlalchemy import Column, SmallInteger, Integer


class SQLAlchemy(_SQLAlchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            raise e


db = _SQLAlchemy()
# 软删除
# 硬删除
class Base(db.Model):
    __abstract__ = True  # 抽象模型，不存在实体表
    create_time = Column('create_time', Integer)
    status = Column(SmallInteger, default=1)  # 1是未删除 0是已删除

    def __init__(self):
        self.create_time = int(datetime.now().timestamp())

    def set_attrs(self, attrs_dict):
        for key, value in attrs_dict.items():
            if hasattr(self, key) and key not in ['id']:
                setattr(self, key, value)

    @property
    def create_datetime(self):
        if self.create_time:
            return datetime.fromtimestamp(self.create_time)
        else:
            return None
# hasattr：判断object对象中是否存在name属性
# getattr：获取object对象的属性的值
# setattr：给object对象的属性赋值value
# https://www.cnblogs.com/zanjiahaoge666/p/7475225.html
